package com.yazi.mxz.behavior.controller;


import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.myframework.smhj.common.tool.DateUtil;
import com.myframework.smhj.jackson.result.StatusResult;
import com.yazi.mxz.behavior.common.BaseController;
import com.yazi.mxz.behavior.entity.enums.UrlType;
import com.yazi.mxz.behavior.entity.repository.AccessLog;
import com.yazi.mxz.behavior.entity.repository.StoreGoodsAccess;
import com.yazi.mxz.behavior.entity.repository.StoreGoodsAccessId;
import com.yazi.mxz.behavior.repository.AccessLogRepository;
import com.yazi.mxz.behavior.repository.StoreGoodsAccessRepository;
import com.yazi.mxz.behavior.repository.StoreGoodsRepository;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller("accessLogController")
@RequestMapping("/accessLog")
public class AccessLogController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(AccessLogController.class);
	
	@Resource
	AccessLogRepository accessLogRepository;
	@Resource
	StoreGoodsRepository storeGoodsRepository;
	@Resource
	StoreGoodsAccessRepository storeGoodsAccessRepository;
	
	/**
	 * url访问日志
	 * @param access
	 * @param req
	 * @param res
	 * @return
	 */
	@RequestMapping(value="/json",headers="X-Requested-With=XMLHttpRequest")
	@ResponseBody
	public StatusResult indexJson(AccessLog access, HttpServletRequest req, HttpServletResponse res) {		
		StatusResult jsonResult = new StatusResult();
		UrlType type;
		Cookie cookie;
		String cookieValue;
		String idValue;
		try {
			
			type = getUrlType(access.getUrl());
			if (null == type) {
				log.debug("忽略：{}", access.getUrl());
				return jsonResult;
			}
			
			cookie = getCookie(COOKIE_KEY_USER_ID, req);
			if (null != cookie) {
				cookieValue = cookie.getValue();
			} else {
				// 时间(毫秒) + 3位随机数
				cookieValue = DateUtil.getTimeStamp() + "" + new Double(Math.random() * 1e3).longValue();
				setCookie(COOKIE_KEY_USER_ID, "" + cookieValue, res);
			}
			
			idValue = DateUtil.getTimeStamp() + "" + new Double(Math.random() * 1e3).longValue();
			
			access.setCookie(Long.parseLong(cookieValue));
			access.setDateTime(DateUtil.getTimeStamp());
			access.setId(Long.parseLong(idValue));
			access.setUrlType(type.ordinal());
			
			log.info("记录：cookie={},type={},url={}", 
					new Object[]{cookieValue, type.getText(), access.getUrl()});
			
			accessLogRepository.insert(access);// TODO 删除过时记录功能未有
					
			analyzeLog(access);
			
			jsonResult.setOk();
			
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			jsonResult.setErrorMessage(e.getMessage());
		}
		return jsonResult;
	}

	private UrlType getUrlType(String url) {
		UrlType type = null;
		int start = url.indexOf("/", url.indexOf("//") + 2);
		url = url.substring(start);// 去掉 域名 http://m.51mxz.com
		// TODO 当前只记录商品详情访问情况
		if (url.indexOf("/storeGoods/detail") > -1) {
			type = UrlType.STORE_GOODS_DETAIL;
		}
		
		return type;
	}
	
	/**
	 * 分析日志,并进行统计处理
	 * @param accessLog
	 */
	private void analyzeLog(AccessLog accessLog) {
		// 商品详情
		if (accessLog.getUrlType() == UrlType.STORE_GOODS_DETAIL.ordinal()) {
			
			String url = accessLog.getUrl();
			int end = url.indexOf("?");
			// 去掉参数
			if (end > -1) {
				url = url.substring(0, end);
			}
			long storeGoodsId = Long.parseLong(url.substring(url.lastIndexOf("/") + 1));
			
			// 查询原有记录
			StoreGoodsAccessId id = new StoreGoodsAccessId();
			id.setCookie(accessLog.getCookie());
			id.setStoreGoodsId(storeGoodsId);
			StoreGoodsAccess sga = storeGoodsAccessRepository.findOne(id);
			
			com.yazi.mxz.behavior.entity.repository.StoreGoods sg4mg = storeGoodsRepository.findOne(storeGoodsId);
			
			if (null == sga) {// 添加
				
				sga = new StoreGoodsAccess();				
				sga.setAccessTime(accessLog.getDateTime());
				sga.setId(id);
				sga.setStoreGoods(sg4mg);
				sga.setLocation(sg4mg.getLocation());
				storeGoodsAccessRepository.insert(sga);
				
			} else {// 更新
				
				sga.setAccessTime(accessLog.getDateTime());
				sga.setLocation(sg4mg.getLocation());
				storeGoodsAccessRepository.save(sga);// TODO 删除过时记录功能未有	
			}
					
		}
	}
}
